package com.alibaba.citrus.cr.mn.order.center.facade.function.asynctask;

import com.alibaba.cz.base.tool.log.Log;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author zhangxiaorui
 * @ClassName AsyncOssUploadProcess
 * @description: TODO
 * @date 2023/05/19 16:45
 * @version: 1.0
 */
public class AsyncTaskOssProcessor {
    private static final Log log = Log.getLogger(AsyncTaskOssProcessor.class);

    /**
     * OSS 配置属性
     */
    private OSS ossClient;
    /**
     * OSS bucketName
     */
    private String bucketName;
    /**
     * OSS 文件路径
     **/
    private String filePath;
    /**
     * OSS 文件路径
     **/
    private String fileName;
    /**
     * OSS 元数据信息
     **/
    private ObjectMetadata objectMetadata;

    public AsyncTaskOssProcessor setOssClient(OSS ossClient) {
        this.ossClient = ossClient;
        return this;
    }

    public AsyncTaskOssProcessor setBucketName(String bucketName) {
        this.bucketName = bucketName;
        return this;
    }

    public AsyncTaskOssProcessor setFilePath(String filePath) {
        this.filePath = filePath;
        return this;
    }

    public AsyncTaskOssProcessor setFileName(String fileName) {
        this.fileName = fileName;
        return this;
    }

    public AsyncTaskOssProcessor setObjectMetadata(ObjectMetadata objectMetadata) {
        this.objectMetadata = objectMetadata;
        return this;
    }

    public PutObjectResult upload(InputStream inputStream) {
        return ossClient.putObject(bucketName, filePath + fileName, inputStream, objectMetadata);
    }

    public String download(String filePathAndFileName) {
        try {
            // filePathAndFileName = filePath + fileName
            OSSObject ossObject = ossClient.getObject(bucketName, filePathAndFileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
            StringBuilder buffer = new StringBuilder();
            while (true) {
                String line = reader.readLine();
                if (line == null) break;
                buffer.append(line);
            }
            reader.close();
            ossObject.close();
            return buffer.toString();
        } catch (Exception e) {
            log.warn("OSS文件下载失败", e);
            return null;
        }
    }
}
